using System.Collections.Generic;
using Life.UI.MVC.Controller;
using Life.UI.MVC.Model;
using Samples.Unity_Dev_Extern._1._0._0.MVC_UI_Extra.Runtime.Scripts.Controller;
using UnityEngine;

namespace Life.UI.MVC.Extra.Controller
{
    public class UIPage : ControllerBase
    {
        private IPageToken _pageToken;
        private List<IUIPageProcessor> _currPageProcessors = new();
        protected override void OnAwake(bool awakeCompleted)
        {
            _pageToken = gameObject.GetComponent<IPageToken>();
            var uiPageProcessors = gameObject.GetComponents<IUIPageProcessor>();
            foreach (var item in uiPageProcessors)
            {
                if (item is MonoBehaviour)
                {
                    var attributes = item.GetType().GetCustomAttributes(true);
                
                    if (attributes.Length > 0)
                    {
                        foreach (var attribute in attributes)
                        {
                            if (attribute is UIPageProcessorAttribute uiPageAttribute && uiPageAttribute.Token == GetControllerType())
                            {
                                _currPageProcessors.Add(item);
                            }
                        }
                    }
                    else
                    {
                        Debug.Log($"继承IUIPageProcessor的类必须添加 UIPageProcessorAttribute : {item.GetType()}, On object:{name}.");
                    }
                }
                else
                {
                    Debug.Log($"{item.GetType().Name} 必须同时继承自 IUIPageProcessor和MonoBehaviour");
                }
            }

            foreach (var uiPageProcessor in _currPageProcessors)
            {
                uiPageProcessor?.OnPageAwake(this, _view);
            }
        }

        protected override int GetControllerType()
        {
            if (_pageToken != null) return _pageToken.GetToken();
            Debug.LogError("使用UIPage需要在对象里添加 继承自IPageToken接口的组件");
            return 0;
        }

        protected override bool OnModelUpdate(ModelBase model)
        {
            foreach (var uiPageProcessor in _currPageProcessors)
            {
                if (uiPageProcessor.OnPageUpdate(this, _view, model))
                {
                    return true;
                }
            }
            return false;
        }

        protected override void OnViewActive()
        {
            foreach (var uiPageProcessor in _currPageProcessors)
            {
                uiPageProcessor.OnViewEnable(this, _view);
            }
        }

        protected override void OnViewHide()
        {
            foreach (var uiPageProcessor in _currPageProcessors)
            {
                uiPageProcessor.OnViewDisable(this, _view);
            }
        }
    }
}
